package com.topisv.tms.web.stock.check;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.topisv.tms.entity.AreaGroup;
import com.topisv.tms.entity.Customers;
import com.topisv.tms.entity.JSONParam;
import com.topisv.tms.entity.PipeStock;
import com.topisv.tms.entity.dto.ChangeInfoDto;
import com.topisv.tms.entity.stock.ViewCusStock;
import com.topisv.tms.entity.stock.check.CheckPlan;
import com.topisv.tms.entity.stock.check.CheckPlanItem;
import com.topisv.tms.service.AreaGroupService;
import com.topisv.tms.service.CustomersService;
import com.topisv.tms.service.PipeStockService;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.service.stock.ViewCusStockService;
import com.topisv.tms.service.stock.check.CheckPlanItemService;
import com.topisv.tms.service.stock.check.CheckPlanService;
import com.topisv.tms.tools.DataTablesUtils;
import com.topisv.tms.tools.ExcelUtils;
import com.topisv.tms.utils.DateUtils;
import com.topisv.tms.utils.JsonUtil;
import com.topisv.tms.web.base.BaseController;

/**
 * 盘点任务_control
 * @author ch
 */
@Controller
@RequestMapping({ "/checkPlan" })
public class CheckPlanController extends BaseController{
	
	private static final Logger logger = LoggerFactory.getLogger(CheckPlanController.class);

	@Autowired
	private AreaGroupService areaGroupService;
	@Autowired
	private CheckPlanService checkPlanService;
	@Autowired
	private CustomersService customersService;
	@Autowired
	private ViewCusStockService  viewCusStockService;
	@Autowired
	private PipeStockService pipeStockService;
	@Autowired
	private CheckPlanItemService checkPlanItemService;

	/**
	 * 导向盘点计划列表页面
	 * 
	 * @param pageNumber
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "v2_toStockCheckPlanList")
	public String toStockCheckPlanList(Model model, ServletRequest request) {
		try {
			// 查出当前用户关联的商家列表
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			List<Customers> customerList = this.customersService.loadCustomerByAuthority(curUser);
			model.addAttribute("customerList", customerList);
			model.addAttribute("userType", curUser.userType);

			// 如果是商家用户,初始化数据
			if ("customer".equals(curUser.userType)) {
				//商家编码 
				String customerCode = curUser.customerCode;
				model.addAttribute("customerCode", customerCode);
				// 初始化仓库数据
				List<AreaGroup> warehouseList = this.areaGroupService.loadAreaGroupByAuthority(curUser, customerCode);
				model.addAttribute("warehouseList", warehouseList);
			}
		} catch (Exception e) {
			
			log.error("error",e);
		}

		return "stock/check/checkPlanList";
	}
	
	/**
	  * 数据源—盘点计划
	  * @param params
	  * @param request
	  * @param response
	  * @throws Exception
	  */
	 @RequestMapping(value="/bindData_plan", method=RequestMethod.POST) 
    public void bindData_plan(@RequestBody JSONParam[] paramJson,HttpServletRequest request, HttpServletResponse response) throws Exception {
		try {
			//变量定义
			PrintWriter out=response.getWriter();
			JSONObject json=new JSONObject();
			Page<CheckPlan> page=null;
			
			//当前用户
			Map<String, Object> param=new HashMap<String, Object>();
           ShiroUser shiroUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			
			//客户端参数
			Map<String, String> paramMap = DataTablesUtils.convertToMap(paramJson);
			String sEcho = paramMap.get("sEcho");  
			int start = Integer.parseInt(paramMap.get("iDisplayStart"));
			int length = Integer.parseInt(paramMap.get("iDisplayLength")); 
            String customerCode = paramMap.get("customerCode");
            String warehouseCode = paramMap.get("warehouseCode");
            String dataRange = paramMap.get("dataRange");
            String status = paramMap.get("status");
			
			//封装查询参数
			if(StringUtils.isEmpty(customerCode)){ //如果商家编码为空，赋予默认权限值
				String customerCodes=this.customersService.loadCustomerByAuthority(shiroUser.jobuuid);
				param.put("customerCodes", customerCodes);
			}else{
				param.put("customerCode", customerCode);
			}
			
			if(StringUtils.isEmpty(warehouseCode)){ //如果仓库编码为空，赋予默认权限值
				String areagroups=shiroUser.areagroups;
				param.put("areagroups", areagroups);
			}else{
				param.put("warehouseCode", warehouseCode);
			}
		
			if(StringUtils.isNotEmpty(dataRange)){
				 Map<String, Date> dataMap=DateUtils.getDateRange(dataRange);
	             Date fromDate=dataMap.get("fromDate");
	             Date toDate=dataMap.get("toDate");
	             param.put("fromDate", fromDate);
	             param.put("toDate", toDate);
			}
			param.put("status", status);
			
			//查询
			int curPage=(start/length)+1;
			page = this.checkPlanService.loadTask(param,curPage, length);
	        List<CheckPlan> planList=page.getContent();
	        
	        //封装查询结果
	        json.put("aaData", planList);
	        json.put("sEcho", sEcho);
	        json.put("iTotalRecords", page.getTotalElements());
	        json.put("iTotalDisplayRecords", page.getTotalElements());
	        
	        out.print(json);
       
		} catch (Exception e) {
			
		}
   } 
	

	/**
	 * 查询动碰sku
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping({ "ajaxQueryChange" })
	public String ajaxQueryChange(ServletRequest request,HttpServletResponse response) {
		try {
			String customerCode = request.getParameter("customerCode");
			String warehouseCode = request.getParameter("warehouseCode");
			String dataRange = request.getParameter("dataRange");

			Map<String, Object> params = new HashMap<String, Object>();
			params.put("customerCode", customerCode);
			params.put("warehouseCode", warehouseCode);
			
			if(StringUtils.isNotEmpty(dataRange)){
				 Map<String, Date> dataMap=DateUtils.getDateRange(dataRange);
	             Date fromDate=dataMap.get("fromDate");
	             Date toDate=dataMap.get("toDate");
	             params.put("fromDate", fromDate);
	             params.put("toDate", toDate);
			}
			
			List<ChangeInfoDto> changeInfoList = this.checkPlanService.queryChange(params);

			JSONObject json = new JSONObject();
			json.put("changeInfoList", changeInfoList);
			PrintWriter out = response.getWriter();
			out.print(json);
		} catch (Exception e) {
			
			log.error("error",e);
		}
		return null;
	}

	/**
	 * 创建动碰盘点任务
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping({ "ajaxCreatePlanChange" })
	@ResponseBody
	public String ajaxCreatePlanChange(ServletRequest request,HttpServletResponse response) {
		try {
			String customerCode = request.getParameter("customerCode");
			String warehouseCode = request.getParameter("warehouseCode");
			String dataRange = request.getParameter("dataRange");

			Map<String, Object> params = new HashMap<String, Object>();
			params.put("customerCode", customerCode);
			params.put("warehouseCode", warehouseCode);
			
			Date fromDate=null;
			Date toDate=null;
			
			if(StringUtils.isNotEmpty(dataRange)){
				 Map<String, Date> dataMap=DateUtils.getDateRange(dataRange);
	             fromDate=dataMap.get("fromDate");
	             toDate=dataMap.get("toDate");
	             params.put("fromDate", fromDate);
	             params.put("toDate", toDate);
			}
			
			this.checkPlanService.createPlanChange(customerCode, warehouseCode,fromDate, toDate);

			return "true";

		} catch (Exception e) {
			
			log.error("error",e);
			return "false";
		}
	}
	
	 @RequestMapping(value={"ajaxCreatePlanSku"}, method={RequestMethod.POST})
	 @ResponseBody
	 public String ajaxCreatePlanSku(ServletRequest request,HttpServletResponse response) {
	    try {
	      String customerCode = request.getParameter("customerCode");
	      String warehouseCode = request.getParameter("warehouseCode");
	      String infos_sku = request.getParameter("infos_sku");
	      this.checkPlanService.createPlanSku(customerCode, warehouseCode,infos_sku);
	      
	      return "true";

	    } catch (Exception e) {
	    	
			log.error("error",e);
			return "false";
	    }
	  }

	/**
	 * Ajax查询商品库存
	 */
	@RequestMapping(value = "ajaxQueryGoods") 
	public String ajaxQueryGoods(ServletRequest request,HttpServletResponse response) {
		try {
			String customerCode = request.getParameter("customerCode");
			String warehouseCode = request.getParameter("warehouseCode");
			String sku = request.getParameter("sku");
			
			Map<String, Object> param=new HashMap<String, Object>();
			param.put("customerCode", customerCode);
			param.put("warehouseCode", warehouseCode);
			param.put("sku", sku);

			List<ViewCusStock> goodsList = this.viewCusStockService.loadByParam(param);
			Map<String, List<ViewCusStock>> map = new HashMap<String, List<ViewCusStock>>();
			map.put("goodsList", goodsList);
			String json = JsonUtil.getObjectString(map);

			PrintWriter out;
			out = response.getWriter();
			out.print(json);

		} catch (Exception e) {
			
			log.error("error",e);
		}
		return null;
	}
	
	/**
	 * 查询已选择的SKU
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping({ "ajaxGetSkuSelected" })
	public String ajaxGetSkuSelected(ServletRequest request,
			HttpServletResponse response) {
		try {
			String infos_sku = request.getParameter("infos_sku");

			if (StringUtils.isEmpty(infos_sku)) {
				return null;
			}

			String[] infoArray = infos_sku.split("【;】");
			List<ViewCusStock> goodsStockList = new ArrayList<ViewCusStock>();

			for (String info : infoArray) {
				String[] tempArray = info.split("【paiu】");
				String _warehouseCode = tempArray[0];
				String _customerCode = tempArray[1];
				String _sku = tempArray[2];

				ViewCusStock viewStock = this.viewCusStockService.loadByCondition(_customerCode,_warehouseCode,_sku);
				if (viewStock != null) {
					goodsStockList.add(viewStock);
				}
			}

			Map<String, Object> map = new HashMap<String, Object>();
			map.put("goodsStockList", goodsStockList);
			String json = JsonUtil.getObjectString(map);
			PrintWriter out = response.getWriter();
			out.print(json);
		} catch (Exception e) {
			log.error("error",e);
		}
		return null;
	}
	
	/**
	 * Ajax查询库位
	 */
	@RequestMapping(value = "ajaxQueryStock") 
	public String ajaxQueryStock(ServletRequest request,HttpServletResponse response) {
		try {
			String customer_code = request.getParameter("customerCode");
			String areagroup_code = request.getParameter("warehouseCode");
			String stock_code = request.getParameter("stockCode");
			
			Map<String, Object> param=new HashMap<String, Object>();
			param.put("customer_code", customer_code);
			param.put("areagroup_code", areagroup_code);
			param.put("stock_code", stock_code);

			List<PipeStock> stockList = this.pipeStockService.loadByParam(param);
			Map<String, List<PipeStock>> map = new HashMap<String, List<PipeStock>>();
			map.put("stockList", stockList);
			String json = JsonUtil.getObjectString(map);

			PrintWriter out;
			out = response.getWriter();
			out.print(json);

		} catch (Exception e) {
			
			log.error("error",e);
		}
		return null;
	}
	
	/**
	 * 查询已选择的库位
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping({ "ajaxGetStockSelected" })
	public String ajaxGetStockSelected(ServletRequest request,HttpServletResponse response) {
		try {
			
			String infos_stock = request.getParameter("infos_stock");

			if (StringUtils.isEmpty(infos_stock)) {
				return null;
			}

			String[] infoArray = infos_stock.split("【;】");
			List<PipeStock> stockList = new ArrayList<PipeStock>();

			for (String info : infoArray) {
				String[] tempArray = info.split("【paiu】");
				String _customerCode = tempArray[0];
				String _warehouseCode = tempArray[1];
				String _stockCode = tempArray[2];

				PipeStock viewStock = this.pipeStockService.loadByCondition(_customerCode,_warehouseCode,_stockCode);
				if (viewStock != null) {
					stockList.add(viewStock);
				}
			}

			Map<String, Object> map = new HashMap<String, Object>();
			map.put("stockList", stockList);
			String json = JsonUtil.getObjectString(map);
			PrintWriter out = response.getWriter();
			out.print(json);
		} catch (Exception e) {
			log.error("error",e);
		}
		return null;
	}
	
	 /**
	  * 创建盘点任务—按库位
	  * @param request
	  * @param response
	  * @return
	  */
	 @RequestMapping(value={"ajaxCreatePlanStock"}, method={RequestMethod.POST})
	 @ResponseBody
	 public String ajaxCreatePlanStock(ServletRequest request,HttpServletResponse response) {
	    try {
	      String customerCode = request.getParameter("customerCode");
	      String warehouseCode = request.getParameter("warehouseCode");
	      String infos_stock = request.getParameter("infos_stock");
	      this.checkPlanService.createPlanStock(customerCode, warehouseCode,infos_stock);
	      
	      return "true";

	    } catch (Exception e) {
	    	
			log.error("error",e);
			return "false";
	    }
	  }
	 
	 /**
	  * 创建盘点任务—按商家
	  * @param request
	  * @param response
	  * @return
	  */
	 @RequestMapping(value={"ajaxCreatePlanCustomer"}, method={RequestMethod.POST})
	 @ResponseBody
	 public String ajaxCreatePlanCustomer(ServletRequest request,HttpServletResponse response) {
	    try {
	      String customerCode = request.getParameter("customerCode");
	      String warehouseCode = request.getParameter("warehouseCode");
	      Date now=new Date();
	      this.checkPlanService.createPlanCustomer(customerCode, warehouseCode,now);
	      
	      return "true";

	    } catch (Exception e) {
	    	
			log.error("error",e);
			return "false";
	    }
	  }
	 
	   /**
		 * 导向点数任务页面
		 * @param model
		 * @param request
		 * @return
		 */
		@RequestMapping(value = "v2_toPlanDetail/{taskId}", method = RequestMethod.GET)
		public String toPlanDetail(@PathVariable("taskId") Long taskId, Model model) {
			try {

				//查询任务
			    CheckPlan  plan=this.checkPlanService.loadById(taskId);
			    
			    //查询任务明细
			    List<CheckPlanItem> itemList=this.checkPlanItemService.loadByPlanCode(plan.getPlanCode());
			    model.addAttribute("itemList", itemList);
			    
			} catch (Exception e) {
				
				log.error("error",e);
			}
			return "stock/check/checkPlanDetail";
		}
		/**
		 * 导出盘点明细
		 * @param planCode
		 * @param response 
		 */
		@RequestMapping(value = "exportCheckPlanDetailExcel/{planCode}", method = RequestMethod.GET)
		public void exportCheckPlanDetailExcel(@PathVariable("planCode") String planCode, HttpServletResponse response){
			try {
				response.setContentType("application/vnd.ms-excel");
				response.setHeader("Content-disposition","attachment; filename=" + planCode + ".xls");
				String[] titles = {"商家名称","仓库网点","库位编码","箱编码","SKU","批次号","生产日期","过期日期","可销(库存)","不可销(库存)","可销(点数)","不可销(点数)"};
				//查询任务明细
			    List<CheckPlanItem> itemList=this.checkPlanItemService.loadByPlanCode(planCode);
			    List<Object[]> rs = new ArrayList<Object[]>();
			    for (CheckPlanItem item : itemList) {
			    	Object[] object = {
			    			item.getCustomer().getCustomerName(),
			    			item.getWarehouse().getGroupName(),
			    			item.getStockCode(),
			    			item.getBoxCode(),
			    			item.getSku(),
			    			item.getBatchCode(),
			    			item.getProductDate(),
			    			item.getExpireDate(),
			    			item.getSalesNum(),
			    			item.getUnusedNum(),
			    			null,
			    			null,
			    			null
			    	};
			    	rs.add(object);
				}
				ExcelUtils.writeExcel(titles,"Sheet1",rs,response.getOutputStream());
			} catch (Exception e) {
				logger.error("some error happed",e);
			}
		}
		
		/**
		  * 取消盘点任务
		  * @param request
		  * @param response
		  * @return
		  */
		 @RequestMapping(value={"ajaxDelCheckPlan"}, method={RequestMethod.POST})
		 public String ajaxDelCheckPlan(ServletRequest request,HttpServletResponse response) {
		    try {
		      Long planId = Long.valueOf(request.getParameter("planId"));
		      String msg=this.checkPlanService.delCheckPlan(planId);
		      
		      
		      Map<String, Object> map = new HashMap<String, Object>();
			  map.put("msg", msg);
			  String json = JsonUtil.getObjectString(map);
			  PrintWriter out = response.getWriter();
			  out.print(json);
		      
		    } catch (Exception e) {
		    	
				log.error("error",e);
		    }
		    return null;
		    
		  }
	 
 	 /**
	  * 定时任务：创建盘点任务
	  */
	 @RequestMapping(value = "autoCreateCheckPlan")
	 public void autoCreateCheckPlan(){
		 try{
			 log.info("执行定时任务：创建盘点计划。时间："+new Date());
			 this.checkPlanService.autoCreateCheckPlan();
		 } catch (Exception e) {
			 log.error("autoCreateCheckPlan error.",e);
		 }
	 } 

}